/*
 * Created on Mar 8, 2005
 * Created by dfhuynh
 */
package edu.mit.simile.longwell.ui.command;

import java.util.Enumeration;
import java.util.Properties;

import javax.servlet.ServletException;

import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;

import edu.mit.simile.longwell.query.Query;
import edu.mit.simile.longwell.ui.FlairMessage;
import edu.mit.simile.longwell.ui.FlairURL;
import edu.mit.simile.longwell.ui.InjectionManager;

/**
 * @author dfhuynh
 */
public class ViewCommand extends CommandBase {
	final static private Logger s_logger = Logger.getLogger(ViewCommand.class);

	protected String m_viewTemplate;

	/**
	 * @param injectionManager
	 */
	public ViewCommand(InjectionManager injectionManager, String viewTemplate) {
		super(injectionManager);
		m_viewTemplate = viewTemplate;
	}

	/* (non-Javadoc)
	 * @see edu.mit.simile.flair.IFlairCommand#execute(edu.mit.simile.flair.FlairMessage)
	 */
	public void execute(FlairMessage msg) throws ServletException {
		try {
			VelocityContext vcContext = createContext(msg);

			String pseudoURI = msg.m_request.getParameter("pseudoURI");
			vcContext.put("object",
				msg.getProfile().getSchemaModel()
					.pseudoURIToResource(pseudoURI));

			Properties properties = new Properties();
			properties.load(msg.m_request.getInputStream());
			
			vcContext.put("outerURL", "");

			Enumeration e = properties.keys();
			while (e.hasMoreElements()) {
				String key = (String) e.nextElement();
				String value = properties.getProperty(key);

				if ("outerQuery".equals(key)) {
					vcContext.put("outerURL",
						new FlairURL(
							msg.m_request.getContextPath(),
							msg.m_profileID,
							new Query(value)));
				}

				vcContext.put(key, value);
			}

			msg.m_ve.mergeTemplate(
				m_viewTemplate,
				vcContext,
				msg.m_response.getWriter());
		} catch (Throwable e) {
			s_logger.error(e);
			e.printStackTrace();
		}

	}
}
